package cn.s1995.sloth.bizs.util.sms;

import cn.hutool.json.JSONUtil;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponseBody;
import darabonba.core.client.ClientOverrideConfiguration;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;

/**
 * 阿里云短信
 */
@Slf4j
@Component
public class AliSms {

    /**
     * 成功的状态码
     */
    public static final String OK = "OK";

    @Resource
    private AliSmsConfiguration configuration;

    public static void main(String[] args) throws Exception {
        AliSms sms = new AliSms();
        buildConf(sms);
        sms.sendSmsForVerificationCode(86, "17602140940", "1234");
    }

    /**
     * 构建配置对象
     *
     * @param provider
     * @throws IOException
     */
    private static void buildConf(AliSms provider) throws IOException {
        AliSmsConfiguration conf = new AliSmsConfiguration();
        provider.configuration = conf;
        Properties properties = new Properties();
        properties.load(AliSms.class.getClassLoader().getResourceAsStream("sms.properties"));
        conf.setAccessKeyId(properties.getProperty("sms.accessKeyId", ""));
        conf.setAccessKeySecret(properties.getProperty("sms.accessKeySecret", ""));
        conf.setRegion(properties.getProperty("sms.region", ""));
        conf.setSignName(properties.getProperty("sms.signName", ""));
        conf.setTemplateCode(properties.getProperty("sms.templateCode", ""));
        conf.setTemplateParam(properties.getProperty("sms.templateParam", ""));
    }

    /**
     * 发送验证码短信
     *
     * @param code              国家码
     * @param mobile           手机号
     * @param verificationCode 验证码
     */
    @SneakyThrows
    public SendSmsResponseBody sendSmsForVerificationCode(Integer code, String mobile, String verificationCode) {
        // Configure Credentials authentication information, including ak, secret, token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(configuration.getAccessKeyId())
                .accessKeySecret(configuration.getAccessKeySecret())
                //.securityToken("<your-token>") // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region(configuration.getRegion()) // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(configuration.getSignName())
                .templateCode(configuration.getTemplateCode())
                .phoneNumbers(mobile)
                .templateParam(String.format(configuration.getTemplateParam(), verificationCode))
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        SendSmsResponse resp = response.get();
        log.info("sendSmsForVerificationCode: {}", JSONUtil.toJsonStr(resp));
        SendSmsResponseBody respBody = resp.getBody();
        // Finally, close the client
        client.close();
        return respBody;
        // "body": {
        //     "code": "isv.AMOUNT_NOT_ENOUGH",
        //     "message": "账户余额不足",
        //     "requestId": "243B647E-8681-5372-B9BC-5194124005BA"
        //   }
    }

}
